let _Vue = null;
export default class VueRouter {
  static install(Vue) {
    if (VueRouter.install.installed) {
      return;
    }
    VueRouter.install.installed = true;

    _Vue = Vue;

    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          this.$router = this.$options.router;
        }
      },
    });
  }
  constructor(options) {
    this.options = options;
    this.mode = options.mode || 'hash';
    this.data = _Vue.observable({
      current: this.mode === 'hash' ? '#/' : '/',
    });
    this.routes = options.routes;
    this.routeMap = {};
  }
  init() {
    this.createRouteMap();
    this.initComponents(_Vue);
    this.initEvent();
  }
  createRouteMap() {
    this.routes.forEach(route => {
      const path = this.mode === 'hash' ? '#' + route.path : route.path;
      this.routeMap[path] = route.component;
    });
  }
  initComponents(Vue) {
    Vue.component('router-link', {
      props: {
        to: String,
      },
      render(h) {
        return h(
          'a',
          {
            attrs: {
              href: this.to,
            },
            on: {
              click:
                this.$router.mode === 'hash'
                  ? this.handleHashClick
                  : this.handleHistoryClick,
            },
          },
          [this.$slots.default]
        );
      },
      methods: {
        handleHashClick(e) {
          location.hash = '#' + this.to;
          this.$router.data.current = '#' + this.to;
          e.preventDefault();
        },
        handleHistoryClick(e) {
          history.pushState({}, '', this.to);
          this.$router.data.current = this.to;
          e.preventDefault();
        },
      },
    });
    Vue.component('router-view', {
      render(h) {
        const { routeMap, current } = this.$router;
        const component = routeMap[current];
        return h(component);
      },
    });
  }
  initEvent() {
    this.mode === 'hash' ? this._initHashEvent() : this._initHistoryEvent();
  }
  _initHashEvent() {
    window.addEventListener('hashchange', () => {
      this.data.current = window.location.hash;
    });
  }
  _initHistoryEvent() {
    window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname;
    });
  }
}
